package com.cctc.rds.nrpc.core.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.type.CollectionType;
import com.fasterxml.jackson.databind.type.SimpleType;

import java.io.IOException;
import java.util.List;

public class JsonUtils {
    private static final ObjectMapper JACKSON;

    static {
        ObjectMapper tmp = new ObjectMapper();
        tmp.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        tmp.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        tmp.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        JACKSON = tmp;
    }

    public static String toJson(Object o) {
        try {
            if (o instanceof String) return (String) o;
            return JACKSON.writeValueAsString(o);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T fromJson(String json, Class<T> tClass) {
        try {
            if (tClass == String.class) return (T) json;
            return JACKSON.readValue(json, tClass);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> List<T> fromJsonList(String jsonList, Class<T> tClass) {
        try {
            if (jsonList == null) return null;
            return JACKSON.readValue(jsonList, CollectionType.construct(List.class, SimpleType.constructUnsafe(tClass)));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
